package services;

import java.util.Iterator;
import java.util.LinkedList;

import objetos.CategoriaObj;
import objetos.ItemVendaObj;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;

import classes.CarrinhoCompraImpl;
import classes.CategoriaImpl;

public class CategoriaService {

	public OMElement efetuarCadastro(OMElement element) {
		
		// Implementacao
		CategoriaImpl ci = new CategoriaImpl();
		
		// Cria elemento de retorno
		OMFactory factory = OMAbstractFactory.getOMFactory();
		OMNamespace ns_return = factory.createOMNamespace("return", "ret");
		OMElement return_element = factory.createOMElement("return", ns_return);
		
		// Objeto
		CategoriaObj categoria = new CategoriaObj();
		
		// Seta objeto
		categoria.loadOMElement(element);
		
		// Preenche retorno
		if ( ci.efetuarCadastro(categoria) ) return_element.setText("true");
		else return_element.setText("false");	
		
		return return_element;
	}
	
	public OMElement atualizarCadastro(OMElement element) {
		
		// Implementacao
		CategoriaImpl ci = new CategoriaImpl();
		
		// Cria elemento de retorno
		OMFactory factory = OMAbstractFactory.getOMFactory();
		OMNamespace ns_return = factory.createOMNamespace("return", "ret");
		OMElement return_element = factory.createOMElement("return", ns_return);
		
		// Objeto
		CategoriaObj categoria = new CategoriaObj();
		
		// Seta objeto
		categoria.loadOMElement(element);
		
		// Preenche retorno
		if ( ci.atualizarCadastro(categoria) ) return_element.setText("true");
		else return_element.setText("false");	
		
		return return_element;
	}
	
	public OMElement removerCadastro(OMElement element) {

		CategoriaImpl ci = new CategoriaImpl();
		
		Integer id = Integer.parseInt(element.getText());
		
		Boolean retorno = ci.removerCadastro(id);
		
		element.setText(retorno.toString());
		
		return element;
	}
	
	public OMElement buscarCategoriaPorNome(OMElement element) {
		
		OMFactory fac = OMAbstractFactory.getOMFactory();
		OMNamespace ns_ret = fac.createOMNamespace("return", "ret");
		OMElement return_element = fac.createOMElement("lista", ns_ret);
		
		CategoriaImpl ci = new CategoriaImpl();
		
		LinkedList<CategoriaObj> list = ci.buscarCategoriaPorNome(element.getText());
		Iterator<CategoriaObj> it = list.iterator();
		
		while(it.hasNext())
			return_element.addChild(it.next().toOMElement());

		return return_element;
	}
}
